__version__ = "1.1.0"
import os
from pathlib import Path

import ruamel.yaml
from ruamel.yaml import safe_load

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.indent(sequence=3, offset=1)


def demo_config():
    """
    加载全局配置文件
    :return:
    """
    with open("config/config.yamltools", "r") as smallfile:
        config = safe_load(smallfile)
        # pprint(config)
    return config


def get_docker_compose_files(path):
    """
    Walks the given path and collects all docker-compose.* files and yields
    """
    for dirpath, dirnames, files in os.walk(path):
        for file in files:
            if "docker-compose." in file:
                yield os.path.join(dirpath, file)


def change_version(version, path):
    """
    Changes the Version of the Example Service
    Note: Example could be a good candidate for an additional commandline
    argument
    """
    docker_compose_files = get_docker_compose_files(path)
    for docker_compose in docker_compose_files:
        with open(docker_compose, "r") as ymlfile:
            docker_config = yaml.load(ymlfile)
            image = docker_config["services"]["example"]["image"]
            string_split = image.split(":")
            string_split.pop()
            string_split.append(version)
            new_image_string = ":".join(string_split)
            docker_config["services"]["example"]["image"] = new_image_string
        with open(docker_compose, "w") as newconf:
            yaml.dump(docker_config, newconf)


def read_docker_compose(path):
    """
    遍历读取docker-compose.yml的内容
    """
    docker_compose_files = get_docker_compose_files(path)
    for docker_compose in docker_compose_files:
        with open(docker_compose, "r") as yml_file:
            docker_config = yaml.load(yml_file)
            # image = docker_config["services"]["mysql"]["image"]
            # print(image)
            services = docker_config["services"]
            # print(type(services)) # ordereddict
            for service, ob in services.items():
                # print(service)
                for k, y in ob.items():
                    if k == "image":
                        print(y)
        print("---")


def update_bcp_dir(volume, bcp_dir):
    """
    替换 volume 中的bcp路径
    :param volume: 原来的volume。例如 /data:/home/model_code/data/make
    :param bcp_dir: bcp路径。例如 /data1
    :return: 替换后的volume。例如 /data1:/home/model_code/data/make
    """
    string_split = volume.split(":")
    string_split.pop()
    string_split.pop()
    string_split.append(bcp_dir)
    string_split.append("/home/model_code/data/make")
    new_bcp_dir = ":".join(string_split)
    return new_bcp_dir


def update_docker_compose_asr(docker_compose_yml_path, asr_dir):
    """
    替换 docker-compose.yml的 volume中的 bcp 路径
    :param docker_compose_yml_path:    docker-compose.yml 全路径
    :param asr_dir:  asr 路径 例如 ./asr
    :return: 无
    """
    with open(docker_compose_yml_path, "r") as yml_file:
        docker_config = yaml.load(yml_file)
        docker_config["services"]["model_code"]["volumes"][3] = update_bcp_dir(
            docker_config["services"]["model_code"]["volumes"][3], asr_dir
        )
    with open(docker_compose_yml_path, "w") as newconf:
        yaml.dump(docker_config, newconf)
    print("替换 " + docker_compose_yml_path + " 中的asr路径为 " + asr_dir + " 完成。")


def update_docker_compose(docker_compose_yml_path, old_content, new_content):
    """
    替换 docker-compose.yml 中的 old_content 为 new_content
    :param docker_compose_yml_path: 例如 docker-compose.yml"
    :param old_content: 例如 “/root/data1:/home/model_code/data/make”
    :param new_content: 例如 “/data:/home/model_code/data/make”
    :return:
    """
    find = {}
    with open(docker_compose_yml_path, "r") as yml_file:
        docker_config = yaml.load(yml_file)
        # 查找 old_content
        services = docker_config["services"]
        for name, services in services.items():
            volumes = dict(services)["volumes"]
            for key, volume in enumerate(volumes):
                # print('key: ', key, 'value: ', volume)
                if volume == old_content:
                    find[name] = key
                    # print(docker_config["services"][name]["volumes"][key])
        # 替换为 new_content
        for n, k in find.items():
            docker_config["services"][n]["volumes"][k] = new_content
    with open(docker_compose_yml_path, "w") as newconf:
        yaml.dump(docker_config, newconf)
    print(docker_compose_yml_path, "已替换 ", old_content, " 为 ", new_content)


def chage_content(old_content, new_content):
    path1 = Path(__file__).resolve()
    path2 = os.path.dirname(path1)
    path3 = os.path.dirname(path2)
    path4 = path3 + "/rsync_conf_files/docker-compose.yml"
    update_docker_compose(path4, old_content, new_content)


if __name__ == "__main__":
    chage_content(
        "/root/data1:/home/model_code/data/make", "/data:/home/model_code/data/make"
    )
